<template>
	<view>
		<scroll-view scroll-y class="page">
			<!-- 头部 -->
			<cu-custom bgColor="bg-rgb" :isBack="true">
				<block slot="backText">返回</block>
				<block slot="content">质检保存</block>
			</cu-custom>
			<!-- 数据列表 -->
			<!-- <view class="list"> -->
			<form @submit="onSubmitPrin">
				<view class="card animation-slide-bottom" :style="[{animationDelay: (index + 1)*0.1 + 's'}]">
					<view class="flex">
						<view class="radius">
							<view class="cu-form-group">
								<view class="title">名称: {{objMsg.productName}}</view>
							</view>
						</view>
					</view>
					<view class="cu-form-group flex justify-start margin-xs p-xs mb-sm borderTop">
						<view class="cu-form-group margin-xs radius">
							<view class="title">客户名称:</view>
							<view>
								<input class="border" placeholder="请输入客户名称" name="customerName" :value="objMsg.client"></input>
							</view>
						</view>
					</view>
					<view class="flex p-xs mb-sm borderTop">
						<!-- <view class="padding-sm margin-xs radius">抽验数量:</view> -->
						<view class="flex-sub margin-xs radius">
							<!-- <input class="border" type="number" placeholder="" name="rejectionNum2"></input> -->
							<view class="cu-form-group">
								<view class="title">抽验总数:</view>
								<view>
									<input class="border" type="number" placeholder="" name="badRate"></input>
								</view>
							</view>
						</view>
						<view class="flex-sub margin-xs radius">
							<!-- <input class="border" type="number" placeholder="" name="rejectionNum2"></input> -->
							<view class="cu-form-group">
								<view class="title">抽验数量:</view>
								<view>
									<input class="border" type="number" placeholder="" name="samplingCount"></input>
								</view>
							</view>
						</view>
					</view>
					<view class="flex-sub margin-xs radius">
						<view class="cu-form-group">
							<view class="title">请选择校验依据</view>
							<view class="lable">
								<picker name="inspectBasis" dataType="1" @change="PickerChange('index', $event)" :value="index" :range="typeArray">
									<view class="picker">
										{{getChooseType}}
										<!-- {{preservationList[index].inspectBasis === -1 ? '校验依据' : typeArray[preservationList[index].inspectBasis]}} -->
									</view>
								</picker>
							</view>
						</view>
					</view>
					<view class="flex justify-start padding-sm margin-xs">
						<view class="title margin-right-sm">抽验方案:</view>
						<view>
							<view v-for="item in samplingType">{{item}}</view>
						</view>
					</view>
					<!-- <view class="flex borderTop">
						<view class="margin-xs flex align-center">抽验方案：</view>
						<view class="flex-sub margin-xs radius">
							<view class="cu-form-group flex-end flex-end">
								<view class="lable">
									<picker name="samplingPlan" dataType="1" @change="PickerChange('samplingIndex', $event)" :value="samplingIndex" :range="samplingType">
										<view class="picker">
											{{getsamplingType}}
										</view>
									</picker>
								</view>
							</view>
						</view>
					</view> -->
					<view class="cu-form-group borderTop">
						<view class="title">外观检验合格否：</view>
						<label>
							<switch name="inspectExterior" @change="handleSwitchWg" :class="switchWg?'checked':''" :checked="switchWg?true:false"></switch>
						</label>
					</view>
					<view class="cu-form-group borderTop">
						<view class="title">功能测试合格否：</view>
						<label>
							<switch name="inspectFunction" @change="handleSwitchGn" :class="switchGn?'checked':''" :checked="switchGn?true:false"></switch>
						</label>
					</view>
					<view class="cu-form-group">
						<view class="title">尺寸规格与包装合格否：</view>
						<view><switch name="inspectSpec" @change="handleSwitchSize" :class="switchSize?'checked':''" :checked="switchSize?true:false"></switch></view>
					</view>
				<!-- 	<view>
						<button @click="addBadInfo" :disabled="badInfoList.length >= badPhenomenas.length">添加不良现象</button>
					</view> -->
					<view class="cu-list grid col-3">
						<button style="margin: 0" @click="addBadInfo" class="cu-item" :disabled="badInfoList.length >= badPhenomenas.length">
							<text class="lg text-gray cuIcon-add"></text>
							<text>添加不良现象</text>
						</button>
					</view>
					<template v-for="(bad, badIndex) in badInfoList">
						<view class="flex p-xs margin-bottom-sm mb-sm borderTop">
							<view class="flex-sub radius">
								<view class="cu-form-group">
									<label>
										<picker name="bodName" dataType="1" @change="PickerBadChange(badIndex, $event)" :value="bad.index" :range="badPhenomenas">
											<view class="picker">
												不良现象:
												{{badPhenomenas[bad.index]}}
											</view>
										</picker>
									</label>
								</view>
							</view>
							<view class="flex-sub radius">
								<view class="cu-form-group">
									<view class="title">数量：</view>
									<label>
										<input class="border" type="number" placeholder="请输入" name="bodNum" v-model="bad.num"></input>
									</label>
								</view>
							</view>
						</view>

					</template>
					<!--
					<view class="flex p-xs margin-bottom-sm mb-sm borderTop">
						<view class="flex-twice radius">
							<view class="cu-form-group">
								<view class="title">
									其他不良现象及数量:
								</view>
								<textarea name="badCauseNum" maxlength="-1"  @input="textareaBInput" placeholder="请输入"></textarea>
							</view>
						</view>
					</view> -->

					<!-- <view class="cu-form-group">
						<view class="title">数量：</view>
						<label>
							<input class="border" type="number" placeholder="请输入" name="rejectionNum1"></input>
						</label>
					</view> -->


					<!-- <view class="cu-form-group">
						<view class="title">
							<picker name="badType" dataType="1" @change="PickerBadChange" :value="badIndex" :range="badPhenomena">
								<view class="picker">
									{{getBadChooseType}}
								</view>
							</picker>
						</view>
						<view class="lable">
							数量：<input class="border" type="number" placeholder="致命缺陷" name="rejectionNum1"></input>
						</view>
					</view> -->
					<view class="bottom">
						<!-- <view class="box">
							<view class="lable">
								检测编码:
							</view>
							<view class="content">
								{{item.projectCode}}
							</view>
						</view>
						<view class="box">
							<view class="lable">
								检测名称:
							</view>
							<view class="content">
								{{item.projectName}}
							</view>
						</view> -->
						<!-- <view class="boxs">
							<view class="lable">
								<text class="title" style="background-color: red;">不良品数量：</text>
							</view>
							<view class="content">
								<input name="badNum" style="width: 400rpx;" type="number" placeholder="请输入不良品数量" />
							</view>
						</view> -->
						<view class="boxs">
							<view class="lable">
								<text class="title" style="background-color: #99CC00;">备注说明：</text>
							</view>
							<view class="content">
								<!-- <input type="" v-model="preservationList[index].num" value="" placeholder="请输入收货数量" /> -->
								<textarea name="badDesc" style="width: 400rpx;" value="" placeholder="请输入" />
							</view>
						</view>
						<view class="cu-form-group align-start" style="padding-top: 10px;">
							<view class="title">拍照上传</view>
							<button @tap="takephoto()" class="cu-btn bg-rgb shadow lg"
								style="width: 100px;">拍照上传</button>
						</view>
						<view class="picture-box">
							<image :src="item" v-for="item in imglist"></image>
							<!-- <view v-for="item in imglist" class="picture"
								:style="{background: 'url(' + item + ') no-repeat',backgroundSize:'cover'}"></view> -->
						</view>
					</view>
				</view>
				<view class="btns">
					<button form-type="submit" class="cu-btn bg-rgb lg">保存</button>
				</view>
			</form>
			<!-- </view> -->

		</scroll-view>
	</view>
</template>

<script>
	export default {
		/** 出货检验 */
		data() {
			const currentDate = this.getDate({
				format: true
			})
			return {
				index: -1,
				badIndex: -1,
				typeArray: ['PCBA外观检验通用规范', '本批首样', '客户特殊要求', '其他'],
				samplingType: ['200pcs以下全检', '200-500pcs抽检20pcs', '500pcs以上按20%比例抽检', 'Ac/Re=0/1'],
				samplingIndex: -1,
				// badPhenomenas: ['极反', '短路', '缺件', '错件', '空焊', '冷焊', '假焊', '刮伤', '脏污', '高跷', '侧立', '浮高', '损件', '偏移', '少锡', '多件', '变形', '针孔', '锡珠', '立牌'],
				badPhenomenas: [],
				badInfoList: [],
				badInfoObj: {},
				date: currentDate,
				inspectGrade: "",
				materielCode: '',
				list: [],
				preservationList: [
					// {
					// 	badPhenomena: '',
					// 	num: 0,
					// }
				],
				objMsg:{},
				switchWg: false,
				switchGn: false,
				switchSize: false,
				textareaBValue: '',
				projectNames: [],
				imglist: [],

			}
		},
		onLoad(e) {
			this.objMsg = uni.getStorageSync('warehousingInspectionDetailObj');
			console.log(this.objMsg)
			this.qualityTesting()
		},
		computed: {
			getChooseType() {
				return this.index === -1 ? '校验依据' : this.typeArray[this.index]
			},
			getsamplingType() {
				return this.samplingIndex === -1 ? '抽样方案' : this.samplingType[this.samplingIndex]
			},
			getBadChooseType() {
				return this.badIndex === -1 ? '不良现象' : this.badPhenomenas[this.badIndex]
			}
			// getBadChooseType() {
			// 	return function(index) {
			// 		return index === -1 ? '不良现象' : this.badPhenomenas[this.badInfoObj['badIndex'+index]]
			// 	}
			// },
		},
		methods: {
			takephoto() {
				let that = this
				let maxUpload = 1
				uni.chooseImage({
					count: 1, // 最多可以选择的图片张数，默认1
					sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
					sourceType: ['camera', 'album'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
					success: (res) => {
						console.log(res);
						const tempFilePaths = res.tempFilePaths
						tempFilePaths.forEach(item=>{
							uni.uploadFile({
								url: that.$http.config.baseUrl + 'sys/common/upload',
								filePath: item,
								method: 'POST',
								name: 'file',
								header:{
									'X-Access-Token': uni.getStorageSync('Access-Token')
								},
								success: function(uploadFileRes) {
									that.imglist = []
									that.modal.show({
										type: 'success',
										content: '上传成功!'
									})
									let result = JSON.parse(uploadFileRes.data)
									if(result.success){
										that.imglist = that.imglist.concat([result.message]); //concat追加到数组
									}else{
										that.modal.show({
											type: 'error',
											content: result.message
										})
									}
								}
							});
						})
					}
				});
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			PickerChange(index,e) {
				this[index] = e.target.value
			},
			PickerBadChange(index,e) {
				this.badInfoList[index].index = e.target.value
			},

			handleSwitchWg(e) {
				this.switchWg = e.detail.value
			},
			handleSwitchGn(e) {
				this.switchGn = e.detail.value
			},
			handleSwitchSize(e) {
				this.switchSize = e.detail.value
			},
			addBadInfo(index) {
				this.badInfoList.push({
					badPhenomena: '',
					num: 0,
					index: -1
				})
			},
			textareaBInput(e) {
				this.textareaBValue = e.detail.value
			},
			qualityTesting() {
				let data = {
					inspectGrade: '262',
					materielCode: this.objMsg.materielCode
				}
				this.$http.get('inspect/mesMaterielCheckprojrct/getByGrade', {
					params: data
				}).then(res => {
					if (res.data.success) {
						this.list = res.data.result
						for (let i = 0; i < this.list.length; i++) {
							let data = {
								num: '',
								txt: '',
								id: this.list[i].id,
								projectName:this.list[i].projectName,
								projectCode:this.list[i].projectCode,
								query2: this.list[i].query2,
								samplingCount: '',
								inspectBasis: -1,
								switchWg: false,
								switchGn: false,
								switchSize: false,
								badInfoList: [],
								badInfoObj: {},
							}
							this.badPhenomenas.push(this.list[i].projectName)
							this.projectNames.push(data['projectName'])
							this.preservationList.push(data)
						}
					} else {
						// this.$tip.error(res.data.message)
						this.modal.show({ type:'error', content:res.data.message })
						setTimeout(function() {
							uni.navigateBack({
								delta: 1
							})
						}, 1000);
					}
				})
			},
			onSubmitPrin(e){
				console.log('formval:', e.detail.value)
				let {badRate,customerName, samplingCount, samplingPlan, inspectBasis, badNum, badDesc, inspectExterior, inspectFunction, inspectSpec} = e.detail.value
				if (customerName.trim().length === 0) {
					this.modal.show({ type:'error', content:'请输入客户名称' })
					return
				}
				if (badRate.trim().length === 0) {
					this.modal.show({ type:'error', content:'请输入抽验总数' })
					return
				}
				if (samplingCount.trim().length === 0) {
					this.modal.show({ type:'error', content:'请输入抽验数量' })
					return
				}
				if (this.index === -1) {
					this.modal.show({ type:'error', content:'请选择校验依据' })
					return
				}
				// if (this.samplingIndex === -1) {
				// 	this.modal.show({ type:'error', content:'请选择抽样方案' })
				// 	return
				// }
				// if (badNum.trim().length === 0) {
				// 	this.modal.show({ type:'error', content:'请输入不良品数量' })
				// 	return
				// }
				uni.showModal({
					title: '提示',
					content: '本次质检是否合格',
					cancelText: '不合格',
					confirmText: '合格',
					success: res => {
						if (res.confirm) {
							uni.showModal({
								title: '入库质检',
								content: '是否保存本次入库质检合格记录？',
								cancelText: '取消',
								confirmText: '保存',
								success: res => {
									if (res.confirm) {
										let bodLogs = []
										let badNums = 0
										this.badInfoList.forEach(item => {
											if (item.index !== -1) {
												bodLogs.push({
													bodName: this.badPhenomenas[item.index],
													bodNum: item.num
												})
												badNums += item.num
											}
										})
										let obj ={
											inspectGrade: '262',
											materielCode: this.objMsg.materielCode,
											materielName: this.objMsg.materielName,
											relatedCode: uni.getStorageSync('warehousingInspectionItem').id,
											inspectQualify:'是',
											inspectVerdict: 'true',
											badRate,
											mesBadnessInfoList:[],
											mesInspectionOut: {
												imglist: this.imglist[0],
												samplingCount,
												customerName,
												samplingPlan: this.samplingType.join(','),
												inspectBasis: this.typeArray[this.index],
												inspectExterior: inspectExterior + '',
												inspectFunction: inspectFunction + '',
												inspectSpec: inspectSpec + '',
												// badNum,
												badDesc,
												inspectDay: this.date
											},
											 bodLogs,
											 // badNum
										}
										for(let i = 0 ; i <this.preservationList.length;i++){
											let data ={
												inspectProject: this.preservationList[i].projectCode,
												inspectResult:this.preservationList[i].txt,
												query2:badNums,
												sysOrgCode: this.preservationList[i].query2
											}
											obj.mesBadnessInfoList.push(data);
										}
										this.$http.post('inspect/mesBadnessHandle/appAdd', obj).then(res => {
											if (res.data.success) {
												// this.$tip.success(res.data.message);
												this.modal.show({ type:'success', content:res.data.message })
												setTimeout(function() {
													uni.navigateBack({
														delta: 1
													})
												}, 1000);
											} else {
												// this.$tip.error(res.data.message)
												this.modal.show({ type:'error', content:res.data.message })
											}
										})
									}
								}
							})
						}else{
							uni.showModal({
								title: '入库质检',
								content: '是否保存本次入库质检不合格记录？',
								cancelText: '取消',
								confirmText: '保存',
								success: res => {
									if (res.confirm) {
										let bodLogs = []
										let badNums = 0
										this.badInfoList.forEach(item => {
											if (item.index !== -1) {
												bodLogs.push({
													bodName: this.badPhenomenas[item.index],
													bodNum: item.num
												})
												badNums += item.num
											}
										})
										let obj ={
											inspectGrade: '262',
											materielCode: this.objMsg.materielCode,
											materielName: this.objMsg.materielName,
											relatedCode: uni.getStorageSync('warehousingInspectionItem').id,
											inspectQualify:'否',
											inspectVerdict: 'false',
											badRate,
											mesBadnessInfoList:[],
											mesInspectionOut: {
												imglist: this.imglist[0],
												samplingCount,
												customerName,
												samplingPlan: this.samplingType[this.samplingIndex],
												inspectBasis: this.typeArray[this.index],
												inspectExterior: inspectExterior + '',
												inspectFunction: inspectFunction + '',
												inspectSpec: inspectSpec + '',
												// badNum,
												badDesc,
												inspectDay: this.date
											},
											 bodLogs,
											 // badNum
										}
										for(let i = 0 ; i <this.preservationList.length;i++){
											let data ={
												inspectProject: this.preservationList[i].projectCode + '-' +this.preservationList[i].name,
												inspectResult:this.preservationList[i].txt,
												query2:badNums,
												sysOrgCode: this.preservationList[i].query2
											}
											obj.mesBadnessInfoList.push(data);
										}
										this.$http.post('inspect/mesBadnessHandle/appAdd', obj).then(res => {
											if (res.data.success) {
												// this.$tip.success(res.data.message);
												this.modal.show({ type:'success', content:res.data.message })
												setTimeout(function() {
													uni.navigateBack({
														delta: 1
													})
												}, 1000);
											} else {
												// this.$tip.error(res.data.message)
												this.modal.show({ type:'error', content:res.data.message })
											}
										})
									}
								}
							})
						}
					}
				})
			}
		},
	}
</script>

<style lang="less">
	.flex-end {
		justify-content: flex-end;
	}
	.padding-sm {
		padding: 11px 0;
	}
	.borderTop {
		border-top: 0.5px solid #eee;
	}
	.border {
		border: 0.5px solid #eee;
	}
	.cu-form-group {
		padding: 0.5px 0;
		// min-height: 0;
		.title {
			height: auto;
			text-align: left;
			white-space: nowrap;
		}
	}
	.card {
		// margin: 30rpx;
		box-shadow: 0px 0px 5rpx 2rpx rgba(0, 0, 0, 0.1);
		border-radius: 10rpx;
		padding: 0 30rpx;
		margin-bottom: 100rpx;
		background-color: white;
	}

	.card .top {
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1rpx solid #F0F0F0;
		padding-bottom: 20rpx;
		font-weight: bold;
	}
	.top .left {
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 400;
			color: #485A75;
			line-height: 50rpx;
		}

	.card .bottom .box {
		display: flex;
		justify-content: space-between;
		padding: 20rpx 0;
	}

	.card .bottom .box .lable {
		width: 25%;
	}

	.card .bottom .box .content {
		width: 74%;
		text-align: right;
	}
	.boxs{
		display: flex;
		justify-content: space-between;
		padding: 20rpx 0;
		align-items: center;
	}
	.boxs .title{
		font-weight: bold;
		padding: 10rpx;
		border-radius: 10rpx;
		color: white;;
	}
	.boxs input {
		border: 2rpx solid red;
		height: 60rpx;
		padding: 10rpx;
		border-radius: 10rpx;
		font-size: 20rpx;
		color: red;
	}
	.boxs input .input-placeholder{
		color: red;
	}
	uni-textarea{
		margin: 0;
		border: 2rpx solid #F0F0F0;
		padding: 10rpx;
		border-radius: 10rpx;
		font-size: 20rpx;
	}
	.list{
		margin-bottom: 120rpx;
	}
	.btns{
		position: fixed;
		width: 100%;
		padding: 0 16px;
		z-index: 999;
		background: white;
		bottom: 0;
		height: 100rpx;
		line-height: 100rpx;
	}
	.cu-btn{
		width: 100%;
		// margin-left: 50rpx;
	}
	.picture-box {
		width: 100%;
		margin-top: 10px;

		.picture {
			width: 100%;
			height: 200px;
			margin-bottom: 10px;
		}
	}
</style>
